<?php

namespace common\jobs;

use Yii;
use common\helpers\FileHelper;
use common\helpers\Utils;

/**
 * 测试队列
 */
class DownloadJob extends BaseRetryableJob {

    public $url;
    public $path;

    /**
     * @param \yii\queue\Queue $queue which pushed and is handling the job
     */
    public function execute($queue) {
        $local = $this->getRemoteImage($this->url);
        if ($local) {
            Utils::pushOSS($local);
        }
    }

    public function getLocalPath() {
        $path = pathinfo($this->path, PATHINFO_DIRNAME);
        $local = Yii::getAlias('@uploads') . '/' . ltrim($path, '/');
        if (FileHelper::createDirectory($local)) {
            return $local;
        }
        return false;
    }

    public function getRemoteImage($url) {
        $filename = pathinfo($url, PATHINFO_BASENAME);
        // 判断本地是否存在改文件
        if (file_exists($this->localPath . '/' . $filename)) {
            return false;
        }
        // 若不存在则获得远程图片
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $imagedata = curl_exec($curl);
        curl_close($curl);

        // 保存远程图片到服务器
        $filePath = $this->localPath . '/' . $filename;
        $tp = @fopen($filePath, 'a');
        fwrite($tp, $imagedata);
        fclose($tp);
        return $this->path;
    }

}
